
#include "Common.h"
#include "DBCStores.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "World.h"
#include "Opcodes.h"
#include "Log.h"
#include "ObjectMgr.h"
#include "Player.h"
#include "Item.h"
#include "Bag.h"
#include "UpdateData.h"
#include "ObjectAccessor.h"
#include "SpellMgr.h"
#include "QueryPackets.h"
#include "LogsDatabaseAccessor.h"

void WorldSession::HandleSplitItemOpcode( WorldPacket & recvData )
{
    //TC_LOG_DEBUG("network.opcode","WORLD: CMSG_SPLIT_ITEM");
    uint8 srcbag, srcslot, dstbag, dstslot, count;

    recvData >> srcbag >> srcslot >> dstbag >> dstslot >> count;
    //TC_LOG_DEBUG("network.opcode","STORAGE: receive srcbag = %u, srcslot = %u, dstbag = %u, dstslot = %u, count = %u", srcbag, srcslot, dstbag, dstslot, count);

    uint16 src = ( (srcbag << 8) | srcslot );
    uint16 dst = ( (dstbag << 8) | dstslot );

    if(src==dst)
        return;

    if (count==0)
        return;                                             //check count - if zero it's fake packet

    if(!_player->IsValidPos(srcbag,srcslot))
    {
        _player->SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr );
        return;
    }

    if(!_player->IsValidPos(dstbag,dstslot))
    {
        _player->SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr );
        return;
    }

    _player->SplitItem( src, dst, count );
}

void WorldSession::HandleSwapInvItemOpcode( WorldPacket & recvData )
{
    //TC_LOG_DEBUG("network.opcode","WORLD: CMSG_SWAP_INV_ITEM");
    uint8 srcslot, dstslot;

    recvData >> srcslot >> dstslot;
    //TC_LOG_DEBUG("network.opcode","STORAGE: receive srcslot = %u, dstslot = %u", srcslot, dstslot);

    // prevent attempt swap same item to current position generated by client at special checting sequence
    if (srcslot == dstslot)
        return;

    if (!_player->IsValidPos(INVENTORY_SLOT_BAG_0, srcslot))
    {
        _player->SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr );
        return;
    }

    if (!_player->IsValidPos(INVENTORY_SLOT_BAG_0, dstslot))
    {
        _player->SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr );
        return;
    }

    if (_player->IsBankPos(INVENTORY_SLOT_BAG_0, srcslot) && !CanUseBank())
    {
        TC_LOG_DEBUG("network", "WORLD: HandleSwapInvItemOpcode - Unit (%s) not found or you can't interact with him.", m_currentBankerGUID.ToString().c_str());
        return;
    }

    if (_player->IsBankPos(INVENTORY_SLOT_BAG_0, dstslot) && !CanUseBank())
    {
        TC_LOG_DEBUG("network", "WORLD: HandleSwapInvItemOpcode - Unit (%s) not found or you can't interact with him.", m_currentBankerGUID.ToString().c_str());
        return;
    }

    uint16 src = ( (INVENTORY_SLOT_BAG_0 << 8) | srcslot );
    uint16 dst = ( (INVENTORY_SLOT_BAG_0 << 8) | dstslot );

    // prevent checters from checting, you little checters !
    if (_player->GetTrader())
    {
        _player->SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, _player->GetItemByPos(src), nullptr );
        return;
    }

    _player->SwapItem( src, dst );
}

void WorldSession::HandleAutoEquipItemSlotOpcode( WorldPacket & recvData )
{
    ObjectGuid itemguid;
    uint8 dstslot;
    recvData >> itemguid >> dstslot;

    // cheating attempt, client should never send opcode in that case
    if(!Player::IsEquipmentPos(INVENTORY_SLOT_BAG_0, dstslot))
        return;

    Item* item = _player->GetItemByGuid(itemguid);
    uint16 dstpos = dstslot | (INVENTORY_SLOT_BAG_0 << 8);

    if(!item || item->GetPos() == dstpos)
        return;

    _player->SwapItem(item->GetPos(), dstpos);
}

void WorldSession::HandleSwapItem( WorldPacket & recvData )
{
    //TC_LOG_DEBUG("network.opcode","WORLD: CMSG_SWAP_ITEM");
    uint8 dstbag, dstslot, srcbag, srcslot;

    recvData >> dstbag >> dstslot >> srcbag >> srcslot ;
    //TC_LOG_DEBUG("network.opcode","STORAGE: receive srcbag = %u, srcslot = %u, dstbag = %u, dstslot = %u", srcbag, srcslot, dstbag, dstslot);

    uint16 src = ( (srcbag << 8) | srcslot );
    uint16 dst = ( (dstbag << 8) | dstslot );

    // prevent attempt swap same item to current position generated by client at special checting sequence
    if(src==dst)
        return;

    if(!_player->IsValidPos(srcbag,srcslot))
    {
        _player->SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr );
        return;
    }

    if(!_player->IsValidPos(dstbag,dstslot))
    {
        _player->SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr );
        return;
    }

    if (_player->IsBankPos(srcbag, srcslot) && !CanUseBank())
    {
        TC_LOG_DEBUG("network", "WORLD: HandleSwapItem - Unit (%s) not found or you can't interact with him.", m_currentBankerGUID.ToString().c_str());
        return;
    }

    if (_player->IsBankPos(dstbag, dstslot) && !CanUseBank())
    {
        TC_LOG_DEBUG("network", "WORLD: HandleSwapItem - Unit (%s) not found or you can't interact with him.", m_currentBankerGUID.ToString().c_str());
        return;
    }

    _player->SwapItem( src, dst );
}

void WorldSession::_HandleAutoEquipItemOpcode(uint8 srcbag, uint8 srcslot)
{
    Item *pSrcItem = _player->GetItemByPos(srcbag, srcslot);
    if (!pSrcItem)
        return;                                             // only at cheat

    if (pSrcItem->m_lootGenerated)                           // prevent swap looting item
    {
        //best error message found for attempting to swap while looting
        _player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, nullptr);
        return;
    }

    uint16 dest;
    uint8 msg = _player->CanEquipItem(NULL_SLOT, dest, pSrcItem, !pSrcItem->IsBag());
    if (msg != EQUIP_ERR_OK)
    {
        _player->SendEquipError(msg, pSrcItem, nullptr);
        return;
    }

    uint16 src = pSrcItem->GetPos();
    if (dest == src)                                           // prevent equip in same slot, only at cheat
        return;

    Item* pDstItem = _player->GetItemByPos(dest);
    if (!pDstItem)                                         // empty slot, simple case
    {
        _player->RemoveItem(srcbag, srcslot, true);
        _player->EquipItem(dest, pSrcItem, true);
        _player->AutoUnequipOffhandIfNeed();
    }
    else                                                    // have currently equipped item, not simple case
    {
        uint8 dstbag = pDstItem->GetBagSlot();
        uint8 dstslot = pDstItem->GetSlot();

        msg = _player->CanUnequipItem(dest, !pSrcItem->IsBag());
        if (msg != EQUIP_ERR_OK)
        {
            _player->SendEquipError(msg, pDstItem, nullptr);
            return;
        }

        // check dest->src move possibility
        ItemPosCountVec sSrc;
        uint16 eSrc = {};
        if (_player->IsInventoryPos(src))
        {
            msg = _player->CanStoreItem(srcbag, srcslot, sSrc, pDstItem, true);
            if (msg != EQUIP_ERR_OK)
                msg = _player->CanStoreItem(srcbag, NULL_SLOT, sSrc, pDstItem, true);
            if (msg != EQUIP_ERR_OK)
                msg = _player->CanStoreItem(NULL_BAG, NULL_SLOT, sSrc, pDstItem, true);
        }
        else if (_player->IsBankPos(src))
        {
            msg = _player->CanBankItem(srcbag, srcslot, sSrc, pDstItem, true);
            if (msg != EQUIP_ERR_OK)
                msg = _player->CanBankItem(srcbag, NULL_SLOT, sSrc, pDstItem, true);
            if (msg != EQUIP_ERR_OK)
                msg = _player->CanBankItem(NULL_BAG, NULL_SLOT, sSrc, pDstItem, true);
        }
        else if (_player->IsEquipmentPos(src))
        {
            msg = _player->CanEquipItem(srcslot, eSrc, pDstItem, true);
            if (msg == EQUIP_ERR_OK)
                msg = _player->CanUnequipItem(eSrc, true);
        }

        if (msg != EQUIP_ERR_OK)
        {
            _player->SendEquipError(msg, pDstItem, pSrcItem);
            return;
        }

        // now do moves, remove...
        _player->RemoveItem(dstbag, dstslot, false);
        _player->RemoveItem(srcbag, srcslot, false);

        // add to dest
        _player->EquipItem(dest, pSrcItem, true);

        // add to src
        if (_player->IsInventoryPos(src))
            _player->StoreItem(sSrc, pDstItem, true);
        else if (_player->IsBankPos(src))
            _player->BankItem(sSrc, pDstItem, true);
        else if (_player->IsEquipmentPos(src))
            _player->EquipItem(eSrc, pDstItem, true);

        _player->AutoUnequipOffhandIfNeed();

        // if inventory item was moved, check if we can remove dependent auras, because they were not removed in Player::RemoveItem (update was set to false)
        // do this after swaps are done, we pass nullptr because both weapons could be swapped and none of them should be ignored
        if ((srcbag == INVENTORY_SLOT_BAG_0 && srcslot < INVENTORY_SLOT_BAG_END) || (dstbag == INVENTORY_SLOT_BAG_0 && dstslot < INVENTORY_SLOT_BAG_END))
            _player->ApplyItemDependentAuras((Item*)nullptr, false);
    }
}

void WorldSession::HandleAutoEquipItemOpcode( WorldPacket & recvData )
{
    //TC_LOG_DEBUG("network.opcode","WORLD: CMSG_AUTOEQUIP_ITEM");
    uint8 srcbag, srcslot;

    recvData >> srcbag >> srcslot;
    //TC_LOG_DEBUG("network.opcode","STORAGE: receive srcbag = %u, srcslot = %u", srcbag, srcslot);

    _HandleAutoEquipItemOpcode(srcbag, srcslot);
}

void WorldSession::HandleDestroyItemOpcode( WorldPacket & recvData )
{
    //TC_LOG_DEBUG("network.opcode","WORLD: CMSG_DESTROYITEM");
    uint8 bag, slot, count, data1, data2, data3;

    recvData >> bag >> slot >> count >> data1 >> data2 >> data3;
    //TC_LOG_DEBUG("network.opcode","STORAGE: receive bag = %u, slot = %u, count = %u", bag, slot, count);

    uint16 pos = (bag << 8) | slot;

    // prevent drop unequipable items (in combat, for example) and non-empty bags
    if(_player->IsEquipmentPos(pos) || _player->IsBagPos(pos))
    {
        uint8 msg = _player->CanUnequipItem( pos, false );
        if( msg != EQUIP_ERR_OK )
        {
            _player->SendEquipError( msg, _player->GetItemByPos(pos), nullptr );
            return;
        }
    }

    Item *pItem  = _player->GetItemByPos( bag, slot );
    if(!pItem)
    {
        _player->SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr );
        return;
    }

    LogsDatabaseAccessor::CharacterItemDelete(_player, pItem);

    if(count)
    {
        uint32 i_count = count;
        _player->DestroyItemCount( pItem, i_count, true );
    }
    else
        _player->DestroyItem( bag, slot, true );
}

// Only _static_ data send in this packet !!!
void WorldSession::HandleItemQuerySingleOpcode(WorldPackets::Query::QueryItemSingle& query)
{
    TC_LOG_DEBUG("network", "STORAGE: Item Query = %u", query.ItemID);

    if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(query.ItemID))
    {
        if (sWorld->getBoolConfig(CONFIG_CACHE_DATA_QUERIES))
            SendPacket(&itemTemplate->QueryData[static_cast<uint32>(GetSessionDbLocaleIndex())]);
        else
        {
            WorldPacket response = itemTemplate->BuildQueryData(GetSessionDbLocaleIndex());
            SendPacket(&response);
        }
    }
    else
    {
        TC_LOG_DEBUG("network", "WORLD: CMSG_ITEM_QUERY_SINGLE - NO item INFO! (ENTRY: %u)", query.ItemID);
        WorldPackets::Query::QueryItemSingleResponse response;
        response.ItemID = query.ItemID;
        SendPacket(response.Write());
    }
}

void WorldSession::HandleReadItem( WorldPacket & recvData )
{
    //TC_LOG_DEBUG("network.opcode", "WORLD: CMSG_READ_ITEM");

    uint8 bag, slot;
    recvData >> bag >> slot;

    //TC_LOG_DEBUG("network.opcode","STORAGE: Read bag = %u, slot = %u", bag, slot);
    Item *pItem = _player->GetItemByPos( bag, slot );

    if( pItem && pItem->GetTemplate()->PageText )
    {
        WorldPacket data;

        uint8 msg = _player->CanUseItem( pItem );
        if( msg == EQUIP_ERR_OK )
        {
            data.Initialize (SMSG_READ_ITEM_OK, 8);
            // TC_LOG_DEBUG("network.opcode","STORAGE: Item page sent");
        }
        else
        {
            data.Initialize( SMSG_READ_ITEM_FAILED, 8 );
            //TC_LOG_DEBUG("network.opcode","STORAGE: Unable to read item");
            _player->SendEquipError( msg, pItem, nullptr );
        }
        data << pItem->GetGUID();
        SendPacket(&data);
    }
    else
        _player->SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr );
}

void WorldSession::HandlePageQuerySkippedOpcode( WorldPacket & recvData )
{
    uint32 itemid;
    ObjectGuid guid;

    recvData >> itemid >> guid;
}

void WorldSession::HandleSellItemOpcode( WorldPacket & recvData )
{
    ObjectGuid vendorguid, itemguid;
    uint8 _count;

    recvData >> vendorguid >> itemguid >> _count;

    // prevent possible overflow, as Trinity uses uint32 for item count
    uint32 count = _count;

    if(!itemguid)
        return;
    
    Creature *pCreature = GetPlayer()->GetNPCIfCanInteractWith(vendorguid, UNIT_NPC_FLAG_VENDOR);
    if (!pCreature)
    {
        TC_LOG_ERROR( "network","WORLD: HandleSellItemOpcode - Unit (GUID: %u) not found or you can't interact with him.", uint32(vendorguid.GetCounter()) );
        _player->SendSellError( SELL_ERR_CANT_FIND_VENDOR, nullptr, itemguid, 0);
        return;
    }

    // remove fake death
    if(GetPlayer()->HasUnitState(UNIT_STATE_DIED))
        GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);

    Item *pItem = _player->GetItemByGuid( itemguid );
    if( pItem )
    {
        // prevent sell not owner item
        if(_player->GetGUID()!=pItem->GetOwnerGUID())
        {
            _player->SendSellError( SELL_ERR_CANT_SELL_ITEM, pCreature, itemguid, 0);
            return;
        }

        // prevent sell non empty bag by drag-and-drop at vendor's item list
        if(pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
        {
            _player->SendSellError( SELL_ERR_CANT_SELL_ITEM, pCreature, itemguid, 0);
            return;
        }

        // prevent sell currently looted item
        if(_player->GetLootGUID()==pItem->GetGUID())
        {
            _player->SendSellError( SELL_ERR_CANT_SELL_ITEM, pCreature, itemguid, 0);
            return;
        }

        // special case at auto sell (sell all)
        if(count==0)
        {
            count = pItem->GetCount();
        }
        else
        {
            // prevent sell more items that exist in stack (possible only not from client)
            if(count > pItem->GetCount())
            {
                _player->SendSellError( SELL_ERR_CANT_SELL_ITEM, pCreature, itemguid, 0);
                return;
            }
        }

        ItemTemplate const *pProto = pItem->GetTemplate();
        if( pProto )
        {
            if( pProto->SellPrice > 0 )
            {
                if(count < pItem->GetCount())               // need split items
                {
                    Item *pNewItem = pItem->CloneItem( count, _player );
                    if (!pNewItem)
                    {
                        TC_LOG_ERROR("network.opcode","WORLD: HandleSellItemOpcode - could not create clone of item %u; count = %u", pItem->GetEntry(), count );
                        _player->SendSellError( SELL_ERR_CANT_SELL_ITEM, pCreature, itemguid, 0);
                        return;
                    }

                    pItem->SetCount( pItem->GetCount() - count );
                    _player->ItemRemovedQuestCheck( pItem->GetEntry(), count );
                    if( _player->IsInWorld() )
                        pItem->SendUpdateToPlayer( _player );
                    pItem->SetState(ITEM_CHANGED, _player);

                    _player->AddItemToBuyBackSlot( pNewItem );
                    if( _player->IsInWorld() )
                        pNewItem->SendUpdateToPlayer( _player );

                    LogsDatabaseAccessor::BuyOrSellItemToVendor(LogsDatabaseAccessor::TRANSACTION_SELL, _player, pNewItem, pCreature);
                }
                else
                {
                    _player->ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount());
                    _player->RemoveItem( pItem->GetBagSlot(), pItem->GetSlot(), true);
                    pItem->RemoveItemFromUpdateQueueOf(_player);
                    _player->AddItemToBuyBackSlot( pItem );

                    LogsDatabaseAccessor::BuyOrSellItemToVendor(LogsDatabaseAccessor::TRANSACTION_SELL, _player, pItem, pCreature);
                }

                _player->ModifyMoney( pProto->SellPrice * count );
            }
            else
                _player->SendSellError( SELL_ERR_CANT_SELL_ITEM, pCreature, itemguid, 0);
            return;
        }
    }
    _player->SendSellError( SELL_ERR_CANT_FIND_ITEM, pCreature, itemguid, 0);
    return;
}

void WorldSession::HandleBuybackItem(WorldPacket & recvData)
{
    ObjectGuid vendorguid;
    uint32 slot;

    recvData >> vendorguid >> slot;

    Creature *pCreature = GetPlayer()->GetNPCIfCanInteractWith(vendorguid, UNIT_NPC_FLAG_VENDOR);
    if (!pCreature)
    {
        TC_LOG_ERROR("network", "WORLD: HandleBuybackItem - Unit (GUID: %u) not found or you can't interact with him.", uint32(vendorguid.GetCounter()) );
        _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, ObjectGuid::Empty, 0);
        return;
    }

    // remove fake death
    if(GetPlayer()->HasUnitState(UNIT_STATE_DIED))
        GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);

    Item *pItem = _player->GetItemFromBuyBackSlot( slot );
    if( pItem )
    {
        uint32 price = _player->GetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + slot - BUYBACK_SLOT_START );
        if( _player->GetMoney() < price )
        {
            _player->SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, pItem->GetEntry(), 0);
            return;
        }

        ItemPosCountVec dest;
        uint8 msg = _player->CanStoreItem( NULL_BAG, NULL_SLOT, dest, pItem, false );
        if( msg == EQUIP_ERR_OK )
        {
            _player->ModifyMoney( -(int32)price );
            _player->RemoveItemFromBuyBackSlot( slot, false );
            _player->ItemAddedQuestCheck( pItem->GetEntry(), pItem->GetCount());
            _player->StoreItem( dest, pItem, true );

            LogsDatabaseAccessor::BuyOrSellItemToVendor(LogsDatabaseAccessor::TRANSACTION_BUYBACK, _player, pItem, pCreature);
        }
        else
            _player->SendEquipError( msg, pItem, nullptr );
        return;
    }
    else
        _player->SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, 0, 0);
}

void WorldSession::HandleBuyItemInSlotOpcode( WorldPacket & recvData )
{
    ObjectGuid vendorguid, bagguid;
    uint32 item;
    uint8 bagslot, count;

    recvData >> vendorguid >> item >> bagguid >> bagslot >> count;

    uint8 bag = NULL_BAG;                                   // init for case invalid bagGUID

    // find bag slot by bag guid
    if (bagguid == _player->GetGUID())
        bag = INVENTORY_SLOT_BAG_0;
    else
    {
        for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
        {
            if (Bag* pBag = _player->GetBagByPos(i))
            {
                if (bagguid == pBag->GetGUID())
                {
                    bag = i;
                    break;
                }
            }
        }
    }

    // bag not found, cheating?
    if (bag == NULL_BAG)
        return;

    GetPlayer()->BuyItemFromVendorSlot(vendorguid, 0, item, count, bag, bagslot);
}

void WorldSession::HandleBuyItemOpcode( WorldPacket & recvData )
{
    ObjectGuid vendorguid;
    uint32 item;
    uint8 count;
    uint8 unused; //sunstrider: reversed from client, always 1

    recvData >> vendorguid >> item >> count >> unused;

    GetPlayer()->BuyItemFromVendorSlot(vendorguid, 0, item, count, NULL_BAG, NULL_SLOT);
}

void WorldSession::HandleListInventoryOpcode(WorldPacket & recvData)
{
    ObjectGuid guid;

    recvData >> guid;

    if(!GetPlayer()->IsAlive())
        return;

    SendListInventory( guid );
}

void WorldSession::SendListInventory(ObjectGuid vendorguid)
{
    Creature* pCreature = GetPlayer()->GetNPCIfCanInteractWith(vendorguid, UNIT_NPC_FLAG_VENDOR);
    if (!pCreature)
    {
        TC_LOG_ERROR("network", "WORLD: SendListInventory - Unit (GUID: %u) not found or you can't interact with him.", uint32(vendorguid.GetCounter()) );
        _player->SendSellError( SELL_ERR_CANT_FIND_VENDOR, nullptr, ObjectGuid::Empty, 0);
        return;
    }

    // remove fake death
    if(GetPlayer()->HasUnitState(UNIT_STATE_DIED))
        GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);

    // Stop the npc if moving
    pCreature->PauseMovement(sWorld->getIntConfig(CONFIG_CREATURE_STOP_FOR_PLAYER));
    pCreature->SetHomePosition(pCreature->GetPosition());

    VendorItemData const* vItems = pCreature->GetVendorItems();
    if(!vItems)
    {
        WorldPacket data(SMSG_LIST_INVENTORY, 8 + 1 + 1);
        data << uint64(vendorguid);
        data << uint8(0);                                   // count == 0, next will be error code
        data << uint8(0);                                   // "Vendor has no inventory"
        SendPacket(&data);
        return;
    }

    uint8 itemCount = vItems->GetItemCount();
    uint8 count = 0;

    WorldPacket data( SMSG_LIST_INVENTORY, (8+1+ itemCount *8*4) );
    data << uint64(vendorguid);
    size_t countPos = data.wpos();
    data << uint8(count);

    float discountMod = _player->GetReputationPriceDiscount(pCreature);

    for(uint8 slot = 0; slot < itemCount; slot++ )
    {
        if(VendorItem const* crItem = vItems->GetItem(slot))
        {
            if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(crItem->item))
            {
                if ((itemTemplate->AllowableClass & _player->GetClassMask()) == 0 && itemTemplate->Bonding == BIND_WHEN_PICKED_UP && !_player->IsGameMaster())
                    continue;

#ifdef LICH_KING
                // Only display items in vendor lists for the team the
                // player is on. If GM on, display all items.
                if (!_player->IsGameMaster() && ((crItem->proto->Flags2 & ITEM_FLAGS_EXTRA_HORDE_ONLY && _player->GetTeamId() == ALLIANCE) || (crItem->proto->Flags2 == ITEM_FLAGS_EXTRA_ALLIANCE_ONLY && _player->GetTeamId() == HORDE)))
                    continue;
#endif

                uint32 leftInStock = !crItem->maxcount ? 0xFFFFFFFF : pCreature->GetVendorItemCurrentCount(crItem);
                /* Why should this be ?
                // Items sold out are not displayed in list
                if (!_player->IsGameMaster() && !leftInStock)
                    continue;
                */

                if (!sConditionMgr->IsObjectMeetingVendorItemConditions(pCreature->GetEntry(), crItem->item, _player, pCreature))
                {
                    TC_LOG_DEBUG("condition", "SendListInventory: conditions not met for creature entry %u item %u", pCreature->GetEntry(), crItem->item);
                    continue;
                }

                // reputation discount
                uint32 price = uint32(floor(itemTemplate->BuyPrice * discountMod));

                data << uint32(slot + 1);  // client expects counting to start at 1
                data << uint32(crItem->item);
                data << uint32(itemTemplate->DisplayInfoID);
                data << uint32(leftInStock);
                data << uint32(price);
                data << uint32(itemTemplate->MaxDurability);
                data << uint32(itemTemplate->BuyCount);
                data << uint32(crItem->ExtendedCost);

                ++count;
                if (count >= MAX_VENDOR_ITEMS)
                    break;
            }
        }
    }

    if (count == 0)
    {
        // count == 0, next will be error code
        data << uint8(0);// "Vendor has no inventory"
        SendPacket(&data);
        return;
    }

    data.put<uint8>(countPos, count);
    SendPacket( &data );
}

void WorldSession::HandleAutoStoreBagItemOpcode( WorldPacket & recvData )
{
    //TC_LOG_DEBUG("network.opcode","WORLD: CMSG_AUTOSTORE_BAG_ITEM");
    uint8 srcbag, srcslot, dstbag;

    recvData >> srcbag >> srcslot >> dstbag;
    //TC_LOG_DEBUG("network.opcode","STORAGE: receive srcbag = %u, srcslot = %u, dstbag = %u", srcbag, srcslot, dstbag);

    Item *pItem = _player->GetItemByPos( srcbag, srcslot );
    if( !pItem )
        return;

    if(!_player->IsValidPos(dstbag,NULL_SLOT))
    {
        _player->SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr );
        return;
    }

    uint16 src = pItem->GetPos();

    // do not allow bag auto-storing
    if (_player->IsBagPos(src)) {
        _player->SendEquipError(EQUIP_ERR_BAG_FULL, pItem, nullptr);
        return;
    }

    // check unequip potability for equipped items and bank bags
    if(_player->IsEquipmentPos ( src ) || _player->IsBagPos ( src ))
    {
        uint8 msg = _player->CanUnequipItem( src, !_player->IsBagPos ( src ));
        if(msg != EQUIP_ERR_OK)
        {
            _player->SendEquipError( msg, pItem, nullptr );
            return;
        }
    }

    ItemPosCountVec dest;
    uint8 msg = _player->CanStoreItem( dstbag, NULL_SLOT, dest, pItem, false );
    if( msg != EQUIP_ERR_OK )
    {
        _player->SendEquipError( msg, pItem, nullptr );
        return;
    }

    // no-op: placed in same slot
    if(dest.size()==1 && dest[0].pos==src)
    {
        // just remove grey item state
        _player->SendEquipError( EQUIP_ERR_NONE, pItem, nullptr );
        return;
    }

    _player->RemoveItem(srcbag, srcslot, true );
    _player->StoreItem( dest, pItem, true );
}

void WorldSession::HandleBuyBankSlotOpcode(WorldPacket& /*recvPacket*/)
{
    uint32 slot = _player->GetByteValue(PLAYER_BYTES_2, 2);

    // next slot
    ++slot;

    //TC_LOG_DEBUG("network.opcode","PLAYER: Buy bank bag slot, slot number = %u", slot);

    BankBagSlotPricesEntry const* slotEntry = sBankBagSlotPricesStore.LookupEntry(slot);
    
    WorldPacket data(SMSG_BUY_BANK_SLOT_RESULT, 4);

    if(!slotEntry) {
        data << uint32(ERR_BANKSLOT_FAILED_TOO_MANY);
        SendPacket(&data);
        return;
    }

    uint32 price = slotEntry->price;

    if (_player->GetMoney() < price) {
        data << uint32(ERR_BANKSLOT_INSUFFICIENT_FUNDS);
        SendPacket(&data);
        return;
    }

    _player->SetByteValue(PLAYER_BYTES_2, 2, slot);
    _player->ModifyMoney(-int32(price));
    
    data << uint32(ERR_BANKSLOT_OK);
    SendPacket(&data);
}

void WorldSession::HandleAutoBankItemOpcode(WorldPacket& recvPacket)
{
    uint8 srcbag, srcslot;
    recvPacket >> srcbag >> srcslot;

    if (!CanUseBank())
    {
        TC_LOG_DEBUG("network", "WORLD: HandleAutoBankItemOpcode - Unit (%s) not found or you can't interact with him.", m_currentBankerGUID.ToString().c_str());
        return;
    }

    Item *pItem = _player->GetItemByPos( srcbag, srcslot );
    if( !pItem )
        return;

    uint16 src = pItem->GetPos();
    if (_player->IsEquipmentPos(src) || _player->IsBagPos(src))
    {
        uint8 msg = _player->CanUnequipItem(src, !_player->IsBagPos(src));
        if (msg != EQUIP_ERR_OK)
        {
            _player->SendEquipError(msg, pItem, nullptr);
            return;
        }
    }
    
    if(_player->IsBankPos(src))
    {
        TC_LOG_ERROR("network","POSSIBLE ITEM DUPLICATION ATTEMPT: Player(GUID: %u Name: %s)::HandleAutoBankItemOpcode - Tried to autobank an item already in bank (slot %u) !", GetPlayer()->GetGUID().GetCounter(), GetPlayer()->GetName().c_str(), srcslot);
        return;
    }

    ItemPosCountVec dest;
    uint8 msg = _player->CanBankItem( NULL_BAG, NULL_SLOT, dest, pItem, false );
    if( msg != EQUIP_ERR_OK )
    {
        _player->SendEquipError( msg, pItem, nullptr );
        return;
    }

    _player->RemoveItem(srcbag, srcslot, true);
    _player->ItemRemovedQuestCheck(pItem->GetEntry(), pItem->GetCount());
    _player->BankItem( dest, pItem, true );
}

void WorldSession::HandleAutoStoreBankItemOpcode(WorldPacket& recvPacket)
{
    uint8 srcbag, srcslot;
    recvPacket >> srcbag >> srcslot;

    if (!CanUseBank())
    {
        TC_LOG_DEBUG("network", "WORLD: HandleAutoStoreBankItemOpcode - Unit (%s) not found or you can't interact with him.", m_currentBankerGUID.ToString().c_str());
        return;
    }

    Item *pItem = _player->GetItemByPos( srcbag, srcslot );
    if( !pItem )
        return;

    uint16 src = pItem->GetPos();
    if (_player->IsEquipmentPos(src) || _player->IsBagPos(src))
    {
        uint8 msg = _player->CanUnequipItem(src, !_player->IsBagPos(src));
        if (msg != EQUIP_ERR_OK)
        {
            _player->SendEquipError(msg, pItem, nullptr);
            return;
        }
    }

    if(_player->IsBankPos(srcbag, srcslot))                 // moving from bank to inventory
    {
        ItemPosCountVec dest;
        uint8 msg = _player->CanStoreItem( NULL_BAG, NULL_SLOT, dest, pItem, false );
        if( msg != EQUIP_ERR_OK )
        {
            _player->SendEquipError( msg, pItem, nullptr );
            return;
        }

        _player->RemoveItem(srcbag, srcslot, true);
        if (Item const* storedItem = _player->StoreItem(dest, pItem, true))
            _player->ItemAddedQuestCheck(storedItem->GetEntry(), storedItem->GetCount());
    }
    else                                                    // moving from inventory to bank
    {
        ItemPosCountVec dest;
        uint8 msg = _player->CanBankItem( NULL_BAG, NULL_SLOT, dest, pItem, false );
        if( msg != EQUIP_ERR_OK )
        {
            _player->SendEquipError( msg, pItem, nullptr );
            return;
        }

        _player->RemoveItem(srcbag, srcslot, true);
        _player->BankItem( dest, pItem, true );
    }
}

void WorldSession::HandleSetAmmoOpcode(WorldPacket & recvData)
{
    if(!GetPlayer()->IsAlive())
    {
        GetPlayer()->SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, nullptr, nullptr );
        return;
    }

    uint32 item;
    recvData >> item;

    if(!item)
        GetPlayer()->RemoveAmmo();
    else
        GetPlayer()->SetAmmo(item);
}

void WorldSession::SendEnchantmentLog(ObjectGuid Target, ObjectGuid Caster, uint32 ItemID, uint32 SpellID)
{
    WorldPacket data(SMSG_ENCHANTMENTLOG, (8 + 8 + 4 + 4 + 1));     // last check 2.0.10
#ifdef LICH_KING
    data << PackedGuid(Target);
    data << PackedGuid(Caster);
#else 
    data << Target;
    data << Caster;
#endif
    data << ItemID;
    data << SpellID;
    data << uint8(0);
    SendPacket(&data);
}

void WorldSession::SendItemEnchantTimeUpdate(ObjectGuid Playerguid, ObjectGuid Itemguid, uint32 slot, uint32 Duration)
{
    // last check 2.0.10 LK ok
    WorldPacket data(SMSG_ITEM_ENCHANT_TIME_UPDATE, (8+4+4+8));
    data << uint64(Itemguid);
    data << uint32(slot);
    data << uint32(Duration);
    data << uint64(Playerguid);
    SendPacket(&data);
}

void WorldSession::HandleItemNameQueryOpcode(WorldPacket & recvData)
{
    uint32 itemid;
    recvData >> itemid;
    ItemTemplate const *pProto = sObjectMgr->GetItemTemplate(itemid);
    if (pProto)
    {
        std::string name = GetLocalizedItemName(pProto);
                                                            // guess size
        WorldPacket data(SMSG_ITEM_NAME_QUERY_RESPONSE, (4+10));
        data << uint32(pProto->ItemId);
        data << name;
        data << uint32(pProto->InventoryType);
        SendPacket(&data);
        return;
    }
    else
        TC_LOG_ERROR("network","WORLD: CMSG_ITEM_NAME_QUERY for item %u failed (unknown item)", itemid);
}

void WorldSession::HandleWrapItemOpcode(WorldPacket& recvData)
{
    uint8 gift_bag, gift_slot, item_bag, item_slot;
    //recvData.hexlike();

    recvData >> gift_bag >> gift_slot;                     // paper
    recvData >> item_bag >> item_slot;                     // item

    Item *gift = _player->GetItemByPos( gift_bag, gift_slot );
    if(!gift)
    {
        _player->SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, gift, nullptr );
        return;
    }

    if(!gift->HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED))// cheating: non-wrapper wrapper
    {
        _player->SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, gift, nullptr );
        return;
    }

    Item *item = _player->GetItemByPos( item_bag, item_slot );

    if( !item )
    {
        _player->SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, item, nullptr );
        return;
    }

    if(item==gift)                                          // not possable with pacjket from real client
    {
        _player->SendEquipError( EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED, item, nullptr );
        return;
    }

    if(item->IsEquipped())
    {
        _player->SendEquipError( EQUIP_ERR_EQUIPPED_CANT_BE_WRAPPED, item, nullptr );
        return;
    }

    if(item->GetGuidValue(ITEM_FIELD_GIFTCREATOR))        // HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED);
    {
        _player->SendEquipError( EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED, item, nullptr );
        return;
    }

    if(item->IsBag())
    {
        _player->SendEquipError( EQUIP_ERR_BAGS_CANT_BE_WRAPPED, item, nullptr );
        return;
    }

    if(item->IsSoulBound())
    {
        _player->SendEquipError( EQUIP_ERR_BOUND_CANT_BE_WRAPPED, item, nullptr );
        return;
    }

    if(item->GetMaxStackCount() != 1)
    {
        _player->SendEquipError( EQUIP_ERR_STACKABLE_CANT_BE_WRAPPED, item, nullptr );
        return;
    }

    // maybe not correct check  (it is better than nothing)
    if(item->GetTemplate()->MaxCount>0)
    {
        _player->SendEquipError( EQUIP_ERR_UNIQUE_CANT_BE_WRAPPED, item, nullptr );
        return;
    }

    SQLTransaction trans = CharacterDatabase.BeginTransaction();
    trans->PAppend("INSERT INTO character_gifts VALUES ('%u', '%u', '%u', '%u')", item->GetOwnerGUID().GetCounter(), item->GetGUID().GetCounter(), item->GetEntry(), item->GetUInt32Value(ITEM_FIELD_FLAGS));
    item->SetEntry(gift->GetEntry());

    switch (item->GetEntry())
    {
        case 5042:  item->SetEntry( 5043); break;
        case 5048:  item->SetEntry( 5044); break;
        case 17303: item->SetEntry(17302); break;
        case 17304: item->SetEntry(17305); break;
        case 17307: item->SetEntry(17308); break;
        case 21830: item->SetEntry(21831); break;
    }
    item->SetGuidValue(ITEM_FIELD_GIFTCREATOR, _player->GetGUID());
    item->SetUInt32Value(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED);
    item->SetState(ITEM_CHANGED, _player);

    if(item->GetState()==ITEM_NEW)                          // save new item, to have alway for `character_gifts` record in `item_instance`
    {
        // after save it will be impossible to remove the item from the queue
        item->RemoveItemFromUpdateQueueOf(_player);
        item->SaveToDB(trans);                                   // item gave inventory record unchanged and can be save standalone
    }
    CharacterDatabase.CommitTransaction(trans);

    uint32 count = 1;
    _player->DestroyItemCount(gift, count, true);
}

void WorldSession::HandleSocketOpcode(WorldPacket& recvData)
{
    ObjectGuid guids[4];
    uint32 GemEnchants[3], OldEnchants[3];
    Item *Gems[3];
    bool SocketBonusActivated, SocketBonusToBeActivated;

    for(ObjectGuid & guid : guids)
        recvData >> guid;

    if(!guids[0])
        return;

    //cheat -> tried to socket same gem multiple times
    if((guids[1] && (guids[1] == guids[2] || guids[1] == guids[3])) || (guids[2] && (guids[2] == guids[3])))
        return;

    Item *itemTarget = _player->GetItemByGuid(guids[0]);
    if(!itemTarget)                                         //missing item to socket
        return;

    //this slot is excepted when applying / removing meta gem bonus
    uint8 slot = itemTarget->IsEquipped() ? itemTarget->GetSlot() : NULL_SLOT;

    for(int i = 0; i < 3; i++)
        Gems[i] = guids[i + 1] ? _player->GetItemByGuid(guids[i + 1]) : nullptr;

    GemPropertiesEntry const *GemProps[3];
    for(int i = 0; i < 3; ++i)                              //get geminfo from dbc storage
    {
        GemProps[i] = (Gems[i]) ? sGemPropertiesStore.LookupEntry(Gems[i]->GetTemplate()->GemProperties) : nullptr;
    }

    for(int i = 0; i < 3; ++i)                              //check for hack maybe
    {
        // tried to put gem in socket where no socket exists / tried to put normal gem in meta socket
        // tried to put meta gem in normal socket
        if( GemProps[i] && ( !itemTarget->GetTemplate()->Socket[i].Color ||
            (itemTarget->GetTemplate()->Socket[i].Color == SOCKET_COLOR_META && GemProps[i]->color != SOCKET_COLOR_META) ||
            (itemTarget->GetTemplate()->Socket[i].Color != SOCKET_COLOR_META && GemProps[i]->color == SOCKET_COLOR_META) ) )
            return;
    }

    for(int i = 0; i < 3; ++i)                              //get new and old enchantments
    {
        GemEnchants[i] = (GemProps[i]) ? GemProps[i]->spellitemenchantement : 0;
        OldEnchants[i] = itemTarget->GetEnchantmentId(EnchantmentSlot(SOCK_ENCHANTMENT_SLOT+i));
    }

    // check unique-equipped conditions
    for(int i = 0; i < 3; ++i)
    {
        if (Gems[i] && (Gems[i]->GetTemplate()->Flags & ITEM_FLAG_UNIQUE_EQUIPPED))
        {
            // for equipped item check all equipment for duplicate equipped gems
            if(itemTarget->IsEquipped())
            {
                if(GetPlayer()->GetItemOrItemWithGemEquipped(Gems[i]->GetEntry()))
                {
                    _player->SendEquipError( EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE, itemTarget, nullptr );
                    return;
                }
            }

            // continue check for case when attempt add 2 similar unique equipped gems in one item.
            for (int j = 0; j < 3; ++j)
            {
                if ((i != j) && (Gems[j]) && (Gems[i]->GetTemplate()->ItemId == Gems[j]->GetTemplate()->ItemId))
                {
                    _player->SendEquipError( EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr );
                    return;
                }
            }
            for (int j = 0; j < 3; ++j)
            {
                if (OldEnchants[j])
                {
                    SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(OldEnchants[j]);
                    if(!enchantEntry)
                        continue;

                    if ((enchantEntry->GemID == Gems[i]->GetTemplate()->ItemId) && (i != j))
                    {
                        _player->SendEquipError( EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr );
                        return;
                    }
                }
            }
        }
    }

    SocketBonusActivated = itemTarget->GemsFitSockets();    //save state of socketbonus
    _player->ToggleMetaGemsActive(slot, false);             //turn off all metagems (except for the target item)

    //if a meta gem is being equipped, all information has to be written to the item before testing if the conditions for the gem are met

    //remove ALL enchants
    for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
        _player->ApplyEnchantment(itemTarget,EnchantmentSlot(enchant_slot), false);

    for(int i = 0; i < 3; ++i)
    {
        if(GemEnchants[i])
        {
            itemTarget->SetEnchantment(EnchantmentSlot(SOCK_ENCHANTMENT_SLOT + i), GemEnchants[i], 0, 0, _player->GetGUID());
            if(Item* guidItem = _player->GetItemByGuid(guids[i + 1]))
                _player->DestroyItem(guidItem->GetBagSlot(), guidItem->GetSlot(), true );
        }
    }

    for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
        _player->ApplyEnchantment(itemTarget,EnchantmentSlot(enchant_slot), true);

    SocketBonusToBeActivated = itemTarget->GemsFitSockets();//current socketbonus state
    if(SocketBonusActivated ^ SocketBonusToBeActivated)     //if there was a change...
    {
        _player->ApplyEnchantment(itemTarget, BONUS_ENCHANTMENT_SLOT, false);
        itemTarget->SetEnchantment(BONUS_ENCHANTMENT_SLOT, (SocketBonusToBeActivated ? itemTarget->GetTemplate()->socketBonus : 0), 0, 0, _player->GetGUID());
        _player->ApplyEnchantment(itemTarget, BONUS_ENCHANTMENT_SLOT, true);
        //it is not displayed, client has an inbuilt system to determine if the bonus is activated
    }

    _player->ToggleMetaGemsActive(slot, true);              //turn on all metagems (except for target item)
}

void WorldSession::HandleCancelTempEnchantmentOpcode(WorldPacket& recvData)
{
    uint32 eslot;

    recvData >> eslot;

    // apply only to equipped item
    if(!Player::IsEquipmentPos(INVENTORY_SLOT_BAG_0,eslot))
        return;

    Item* item = GetPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, eslot);

    if(!item)
        return;

    if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
        return;

    GetPlayer()->ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
    item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
}

/**
* Handles the packet sent by the client when requesting information about item text.
*
* This function is called when player clicks on item which has some flag set
  Old comment: this function is called when client needs mail message body, or when player clicks on item which has ITEM_FIELD_ITEM_TEXT_ID > 0
*/
void WorldSession::HandleItemTextQuery(WorldPacket& recvData)
{
#ifdef LICH_KING
    ObjectGuid itemGuid;
    recvData >> itemGuid;

    TC_LOG_DEBUG("network", "CMSG_ITEM_TEXT_QUERY %s", itemGuid.ToString().c_str());

    WorldPacket data(SMSG_ITEM_TEXT_QUERY_RESPONSE, (4 + 10));    // guess size

    if (Item* item = _player->GetItemByGuid(itemGuid))
    {
        data << uint8(0);                                       // has text
        data << uint64(itemGuid);                               // item guid
        data << item->GetText();
    }
    else
    {
        data << uint8(1);                                       // no text
    }
#else
    uint32 itemTextId;
    uint32 mailId; // this value can be item id in bag, but it is also mail id
    uint32 unk;    // maybe something like state - 0x70000000

    recvData >> itemTextId >> mailId >> unk;

    WorldPacket data(SMSG_ITEM_TEXT_QUERY_RESPONSE, (12)); // guess size
    data << itemTextId;
    data <<  sObjectMgr->GetItemText(itemTextId);
#endif

    SendPacket(&data);
}

bool WorldSession::CanUseBank(ObjectGuid bankerGUID) const
{
    // bankerGUID parameter is optional, set to 0 by default.
    if (!bankerGUID)
        bankerGUID = m_currentBankerGUID;

    bool isUsingBankCommand = (bankerGUID == GetPlayer()->GetGUID() && bankerGUID == m_currentBankerGUID);

    if (!isUsingBankCommand)
    {
        Creature* creature = GetPlayer()->GetNPCIfCanInteractWith(bankerGUID, UNIT_NPC_FLAG_BANKER);
        if (!creature)
            return false;
    }

    return true;
}